using System;
using System.Windows.Forms;
using BLL.TicketBLL;
using Model;
using System.Collections.Generic;
using System.Data; // 添加Data命名空间
using System.Diagnostics; // 用于调试

namespace MDMUI.TicketManagement
{
    public partial class TicketCreation : Form
    {
        private readonly TicketCreationBLL _ticketBLL = new TicketCreationBLL();

        public TicketCreation()
        {
            InitializeComponent();
            InitializeComboBoxData(); // 初始化下拉框数据
        }

        // 窗体加载事件 - 修改顺序
        private void TicketCreation_Load(object sender, EventArgs e)
        {
            InitializeDataGridView(); // 1. 先初始化列
            LoadWorkOrders();         // 2. 再加载数据
        }

        // 自定义工单类型comboBox下拉数据
        private List<Object> _workOrderTypes = new List<Object>
        {
            new { TypeCode = "DF6 ", Description = "DRAM非监管仓加工工单" },
            new { TypeCode = "DM1", Description = "DRAM 非监管 WX工单" },
            new { TypeCode = "DM2", Description = "DRAM非监管仓返工工单" },
            new { TypeCode = "DM6", Description = "DRAM一般贸易批量工单" },
            new { TypeCode = "DM8", Description = "DRAM一般贸易试产工单" },
            new { TypeCode = "DMN", Description = "DRAM 国内非监管RMA..." },
            new { TypeCode = "DMR", Description = "DRAM 国外非监管RMA..." },
            new { TypeCode = "DRN", Description = "SSD 国内RMA返修工单" },
            new { TypeCode = "DRW", Description = "SSD 国外RMA返修工单" },
            new { TypeCode = "DU2", Description = "DRAM非监管仓返工工单" },
            new { TypeCode = "SB1", Description = "SSD惠州标准WX工单" },
            new { TypeCode = "SB2", Description = "SSD惠州非标准WX工单" }
        };

        // 初始化工单类型comboBox下拉框数据
        private void InitializeComboBoxData()
        {
            // 绑定自定义工单类型到ComboBox
            工单类型comboBox.DataSource = _workOrderTypes;
            工单类型comboBox.DisplayMember = "Description";
            工单类型comboBox.ValueMember = "TypeCode";
            工单类型comboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

            // 自定义工单类型comboBox下拉项的绘制方式
            工单类型comboBox.DrawMode = DrawMode.OwnerDrawVariable;
            工单类型comboBox.DropDownHeight = 200; // 设置合适的高度
            工单类型comboBox.DropDownWidth = 400;
            工单类型comboBox.DrawItem += 工单类型comboBox_DrawItem;

            // 绑定产品编号到下拉框
            List<Product> products = _ticketBLL.GetAllProducts();
            产品编号comboBox.DataSource = products;
            产品编号comboBox.DisplayMember = "ProductId";
            产品编号comboBox.ValueMember = "ProductId";

            // 确保初始时不选中任何项
            工单类型comboBox.SelectedIndex = -1;
            产品编号comboBox.SelectedIndex = -1;

            // 绑定按钮点击事件
            添加btn.Click += 添加btn_Click;
            清空btn.Click += 清空btn_Click;
            工单类型comboBox.SelectedIndexChanged += 工单类型comboBox_SelectedIndexChanged;
        }

        // 自定义绘制下拉项
        private void 工单类型comboBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;

            // 使用默认的背景绘制（包括选中状态）
            e.DrawBackground();

            // 获取当前项
            object item = 工单类型comboBox.Items[e.Index];
            var type = item.GetType();
            string typeCode = type.GetProperty("TypeCode").GetValue(item).ToString();
            string description = type.GetProperty("Description").GetValue(item).ToString();

            // 使用系统默认的前景色（自动适应选中/未选中状态）
            using (var textBrush = new SolidBrush(e.ForeColor))
            using (var boldFont = new Font(工单类型comboBox.Font, FontStyle.Bold))
            using (var normalFont = new Font(工单类型comboBox.Font, FontStyle.Regular))
            {
                // 绘制 TypeCode（左对齐，加粗）
                e.Graphics.DrawString(typeCode, boldFont, textBrush,
                    new RectangleF(e.Bounds.X + 5, e.Bounds.Y, 80, e.Bounds.Height));

                // 绘制 Description（右对齐，普通字体）
                e.Graphics.DrawString(description, normalFont, textBrush,
                    new RectangleF(e.Bounds.X + 100, e.Bounds.Y, e.Bounds.Width - 105, e.Bounds.Height));
            }

            // 使用默认的焦点矩形
            e.DrawFocusRectangle();
        }

        // 选中产品编号时自动填充其他字段
        private void 产品编号comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取选中的 Product 对象
            Product selectedProduct = (Product)产品编号comboBox.SelectedItem;

            // 检测是否真的选中了项
            if (产品编号comboBox.SelectedItem == null)
            {
                // 可选：清空所有文本框
                产品编号txtBox.Clear();
                产品类型txtBox.Clear();
                工艺流程号txtBox1.Clear();
                BOM编号txtBox1.Clear();
                单位txtBox.Clear();
                封装形式txtBox.Clear();
                return;
            }

            // 安全获取选中的 Product 对象
            if (产品编号comboBox.SelectedItem != null)
            {
                // 填充数据
                产品编号txtBox.Text = selectedProduct.ProductId.ToString();
                产品类型txtBox.Text = selectedProduct.ProductType;
                工艺流程号txtBox1.Text = selectedProduct.TotalProcessId.ToString();
                BOM编号txtBox1.Text = selectedProduct.MaterialId.ToString();
                单位txtBox.Text = selectedProduct.Unit;
                封装形式txtBox.Text = selectedProduct.PackagingForm;
            }
        }

        // 修改InitializeDataGridView方法 - 修复列名显示
        private void InitializeDataGridView()
        {
            工单列表DGV.AutoGenerateColumns = false;
            工单列表DGV.Columns.Clear();

            // 使用完整列名和中文标题
            var columns = new (string Name, string HeaderText, int Width, string Format)[]
            {
                ("WorkOrderId", "工单ID", 80, ""),
                ("ProductId", "产品ID", 80, ""),
                ("WorkOrderType", "工单类型", 100, ""),
                ("DetailedType", "详细类型", 80, ""),
                ("WorkOrderDescription", "工单说明", 150, ""),
                ("WorkOrderStatus", "工单状态", 80, ""),
                ("PlannedStartDate", "计划开始日期", 150, "yyyy-MM-dd HH:mm"),
                ("PlannedDueDate", "计划结束日期", 150, "yyyy-MM-dd HH:mm"),
                ("TestProgramNumber", "测试程序号", 80, ""),
                ("CompanyNumber", "公司ID", 80, ""),
                ("ProductType", "产品类型", 120, ""),
                ("TotalProcessId", "工艺流程号", 120, "")
            };

            foreach (var col in columns)
            {
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn
                {
                    Name = col.Name,
                    HeaderText = col.HeaderText,
                    Width = col.Width,
                    DataPropertyName = col.Name
                };

                if (!string.IsNullOrEmpty(col.Format))
                {
                    column.DefaultCellStyle.Format = col.Format;
                }

                工单列表DGV.Columns.Add(column);
            }

            工单列表DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            工单列表DGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }

        // 修改LoadWorkOrders方法 - 修复线程问题和绑定方式
        private void LoadWorkOrders()
        {
            try
            {
                // 确保窗口句柄已创建
                if (!this.IsHandleCreated) return;

                List<Dictionary<string, object>> workOrders = _ticketBLL.GetAllWorkOrdersWithProduct();

                // 调试输出
                Debug.WriteLine($"获取到 {workOrders?.Count ?? 0} 条记录");
                if (workOrders?.Count > 0)
                {
                    var first = workOrders[0];
                    Debug.WriteLine($"首条记录: {string.Join(", ", first.Select(kv => $"{kv.Key}={kv.Value}"))}");
                }

                // 将字典列表转换为DataTable
                DataTable table = new DataTable();
                if (workOrders?.Count > 0)
                {
                    // 创建列（确保列名正确）
                    foreach (var key in workOrders[0].Keys)
                    {
                        table.Columns.Add(key.ToString());
                    }

                    // 添加行数据
                    foreach (var dict in workOrders)
                    {
                        DataRow row = table.NewRow();
                        foreach (var pair in dict)
                        {
                            row[pair.Key] = pair.Value;
                        }
                        table.Rows.Add(row);
                    }
                }

                // 使用BeginInvoke确保线程安全
                this.BeginInvoke((MethodInvoker)delegate
                {
                    工单列表DGV.DataSource = table;

                    // 应用日期格式（如果转换中丢失）
                    foreach (DataGridViewColumn column in 工单列表DGV.Columns)
                    {
                        if (column.Name.Contains("Date"))
                        {
                            column.DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工单失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 添加按钮点击事件
        private void 添加btn_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(工单类型txtBox.Text))
                {
                    MessageBox.Show("请输入工单类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    工单类型txtBox.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(计划数量txtBox.Text))
                {
                    MessageBox.Show("请输入计划数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    计划数量txtBox.Focus();
                    return;
                }

                if (计划开始日期dateTime.Value > 计划结束日期dateTime.Value)
                {
                    MessageBox.Show("计划开始日期不能晚于计划结束日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    计划开始日期.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(用户编号txtBox.Text) && string.IsNullOrEmpty(备注txtBox.Text))
                {
                    MessageBox.Show("备注或用户编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    用户编号txtBox.Focus();
                    备注txtBox.Focus();
                    return;
                }

                // 创建WorkOrder对象并赋值
                WorkOrder newWorkOrder = new WorkOrder
                {
                    WorkOrderType = 工单类型comboBox.SelectedValue?.ToString() ?? "", // 安全获取选中的TypeCode
                    DetailedType = 工单类型txtBox.Text.Trim(), // 详细类型
                    ProductId = int.Parse(产品编号comboBox.Text.Trim()), // 产品ID
                    WorkOrderDescription = 工单说明txtBox.Text.Trim(),
                    WorkOrderStatus = "待投产",
                    PlannedStartDate = 计划开始日期dateTime.Value,
                    PlannedDueDate = 计划结束日期dateTime.Value,
                    PlannedQuantity = int.Parse(计划数量txtBox.Text.Trim()),
                    TestProgramNumber = 1, // 默认值
                    CompanyNumber = 1      // 默认值
                };

                // 调用BLL层方法添加工单
                int result = _ticketBLL.AddWorkOrder(newWorkOrder);

                if (result > 0)
                {
                    MessageBox.Show("工单添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearInputs();           // 清空输入框
                    LoadWorkOrders();        // 重新加载工单列表
                }
                else
                {
                    MessageBox.Show("工单添加失败，请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加工单时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 清空按钮点击事件
        private void 清空btn_Click(object sender, EventArgs e)
        {
            ClearInputs();
        }

        // 清空所有输入框
        private void ClearInputs()
        {
            工单类型comboBox.SelectedIndex = -1; // 清空ComboBox选择
            产品编号comboBox.SelectedIndex = -1;
            产品类型txtBox.Clear();
            产品编号txtBox.Clear();
            工单说明txtBox.Clear();
            计划开始日期dateTime.Value = DateTime.Now;
            计划结束日期dateTime.Value = DateTime.Now.AddDays(7); // 默认结束日期为开始日期后7天
            计划数量txtBox.Clear();
            封装形式txtBox.Clear();
            工艺流程号txtBox1.Clear();
            BOM编号txtBox1.Clear();
            单位txtBox.Clear();
            用户编号txtBox.Clear();
            客户批次号txtBox.Clear();
            备注txtBox.Clear();
            工单类型txtBox.Clear();            
        }

        // 选中工单类型comboBox项，就显示工单类型txtBox的固定值
        private void 工单类型comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 直接检查 SelectedItem 是否为 null
            if (工单类型comboBox.SelectedItem == null)
            {
                工单类型txtBox.Clear();
            }
            else
            {
                // 当有任何有效选择时，就设置固定值
                工单类型txtBox.Text = "Production";
            }
        }

        private void 确认btn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(用户编号txtBox.Text) || string.IsNullOrEmpty(备注txtBox.Text))
            {
                MessageBox.Show("备注或用户编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                用户编号txtBox.Focus();
                备注txtBox.Focus();
                return;
            }
            else if (用户编号txtBox.Text != null && 备注txtBox.Text != null)
            {
                MessageBox.Show("是否创建工", "确认操作", MessageBoxButtons.YesNo);
            }
        }
    }
}